﻿using ApiManage.Core.Utils;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Rhonin.Common;
using Rhonin.Common.Entity.Api;
using Rhonin.Common.Entity.UserTicket;
using Rhonin.Common.Utilities;

namespace ApiManage.Svc.Controllers
{
    /// <inheritdoc />
    /// <summary>
    /// 基础控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public abstract class BaseController : Controller
    {
        /// <summary>
        /// 登录用户信息
        /// </summary>
        public static UserTicket Ticket { get; private set; }
        /// <summary>
        /// 登录用户Id
        /// </summary>
        protected string UserId
        {
            get
            {
                if (Ticket == null)
                {
                    return null;
                }
                return !Ticket.IsIn ? null : Ticket.CUI.UserId;
            }
        }
        /// <inheritdoc />
        /// <summary>
        /// 执行前获取票据
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Ticket = context.HttpContext.GetLoginUser();
        }

        private static string Server => ApiResultInitializer.ShowServer
            ? IpUtils.GetHostIp()
            : null;
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected ApiResult<T> CreateResult<T>(T obj) => Create(obj);

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected ApiResult CreateSuccess() => Create();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ApiResult CreateError(string message) => Create(ResultStatus.Fail, message);
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static ApiResult Create() => Create(ResultStatus.Success, null);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="status"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static ApiResult Create(ResultStatus status, string message) => new ApiResult
        {
            Status = status,
            Server = Server,
            Message = message
        };
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ApiResult<T> Create<T>(T data) => new ApiResult<T>
        {
            Status = ResultStatus.Success,
            Server = Server,
            Data = data
        };

    }
}
